import crypto from 'crypto';
import http from 'http';
import nodemailer from 'nodemailer';
import formidable from 'formidable';
import fs from 'fs';

//处理文件上传
export function upload(req, res) {
	let form = new formidable.IncomingForm();
	//设置编辑
	form.encoding = 'utf-8';
	//设置文件存储路径
	form.uploadDir = "web/uploads/";
	//保留后缀
	form.keepExtensions = true;
	//设置单文件大小限制    
	form.maxFieldsSize = 2 * 1024 * 1024;
	//form.maxFields = 1000;  设置所以文件的大小总和
	form.parse(req, function (err, fields, files) {
		let ret
		if (err) {
			ret = { errcode: -1, data: files }
		} else {
			ret = { errcode: 0, data: files }
			let tmpPath = files['xr_system'].path
			let newPath = form.uploadDir + fields.full_name
			fs.renameSync(tmpPath, newPath);
		}
		res.writeHead(200, { 'content-type': 'text/plain' });
		res.end(JSON.stringify(ret))
	});
}

export function HomePage(req, res) {
	console.log(req.url)
	res.sendfile("web/wechat/index.html")
}

export function debug(name, value) {
	var val = value
	if (typeof value === 'object') {
		val = JSON.stringify(value)
	}
	console.log(name + '=' + val)
}

function byte2string16(buff) {
	var console_msg = ''
	for (var i = 0; i < buff.length; i++) {
		if (console_msg != '') {
			console_msg += ','
		}
		console_msg += buff[i].toString(16);
	}
	return '[' + console_msg + ']';
}

//以16进制方式打印数组
export function bytearr2string(buff) {
	byte2string16(buff)
}

export function chineseSort(orderby, chineseFields) {
	let orderarr = orderby.split(" ");
	for (let a in chineseFields) {
		if (orderarr[0] == a) {
			return "convert(" + orderarr[0] + " using gb2312) " + orderarr[1];
		}
	}
	return orderby;
}

// 得到总页面数
export function getPages(records, PageCount) {
	return Math.ceil(records / PageCount);
}
export function getPageSql(pageIndex, pageCount) {
	return " limit " + (pageIndex - 1) * pageCount + ", " + pageCount + " ";
}


//加密
export function encryption(data, key) {
	const iv = "AAAAAAAAAAAAAAAA";
	return encrypt(data, key, iv)
}

//加密
exports.encrypt = function (data, key, iv) {
	const clearEncoding = 'utf8';
	const cipherEncoding = 'base64';
	let cipherChunks = [];
	const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
	cipher.setAutoPadding(true);

	cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
	cipherChunks.push(cipher.final(cipherEncoding));
	return cipherChunks.join('');
}

//加密
export function decrypt(crypted, key) {
	const iv = "AAAAAAAAAAAAAAAA";
	crypted = new Buffer(crypted, 'base64').toString('binary');
	const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
	const decoded = decipher.update(crypted, 'binary', 'utf8');
	decoded += decipher.final('utf8');
	return decoded;
}


//强调转成16进制输出
export function toHex16(card_no) {
	if (!isNaN(card_no)) {
		card_no = card_no + '';
	}
	if (card_no.substring(0, 2).toUpperCase() == "0X") {
		return card_no.substring(2).toUpperCase();
	} else {
		let no = parseInt(card_no)
		if (isNaN(no)) {
			return '';
		} else {
			return no.toString(16).toUpperCase();
		}
	}
}


export function rowstoHex16(array) {
	for (let i = 0; i < array.length; i++) {
		array[i].card_no = this.toHex16(array[i].card_no)
	}
	return array;
}

//获得6位随机数
export function MathRand() {
	let num = "";
	for (let i = 0; i < 6; i++) {
		num += Math.floor(Math.random() * 10);
	}
	return num;
}

export function randomChar(l) {
	const x = "0123456789qwertyuioplkjhgfdsazxcvbnm";
	let tmp = "";
	for (let i = 0; i < l; i++) {
		tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
	}
	return tmp;
}



//判断一个变量是否为空或是没有定义
export function isEmpty(value) {
	if (value == undefined || value == null) {
		return true;
	}
	return value == '' && typeof (value) == 'string';
}
export function send_mqtt(topic, payload) {
	const client = new MQTTClient('aidoor.net', 1883, {});
	console.log('try to connect aidoor.net 1883');
	client.connect(function () {
		console.log('connect aidoor.net success');
		send_mqtt_msg(client, topic, payload)
		//5秒后断开连接
		const disconnect = function () {
			client.disconnect(function () {
				console.log('连接断开');
			});
		}
		// setTimeout('disconnect()',5000);
	});
	client.on('error', function (err) {
		console.log('send_mqtt error ' + err);
	});
}
function isArray(object) {
	return object && typeof object === 'object' && Array == object.constructor;
}

export function CheckDateTime(str) {
	const reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
	const r = str.match(reg);
	if (r == null) return false;
	r[2] = r[2] - 1;
	const d = new Date(r[1], r[2], r[3], r[4], r[5], r[6]);
	if (d.getFullYear() != r[1]) return false;
	if (d.getMonth() != r[2]) return false;
	if (d.getDate() != r[3]) return false;
	if (d.getHours() != r[4]) return false;
	if (d.getMinutes() != r[5]) return false;
	if (d.getSeconds() != r[6]) return false;
	return true;
}

export function send_sms(phoneNo, smsTxt, callback) {
	if (phoneNo == '13173747302') {
		//测试号码，不发短信
		return;
	}
	var data = qs.stringify({
		UserID: 169830,
		Account: 'admin',
		Password: '9CVFG4',
		Phones: phoneNo,
		Content: smsTxt + '【时光宝盒】',
		SendTime: '',
		SendType: 1,
		PostFixNumber: ''
	});
	var options = {
		hostname: '113.106.16.55',
		port: 8080,
		path: '/GateWay/Services.asmx/DirectSend?' + data,
		method: 'GET'
	};
	//发送请求
	var req = http.request(options, function (res) {
		res.setEncoding('utf8');
		res.on('data', function (chunk) {
			console.log(chunk);
		});
	});
	//如果有错误会输出错误
	req.on('error', function (e) {
		console.log('错误：' + e.message);
	});
	req.end();
}





//邮件提交错误
export function sendEmail(from, to, subject, body) {
	const smtpTransport = nodemailer.createTransport({
		host: 'smtp.exmail.qq.com',
		secureConnection: true, // use SSL
		port: 465,
		auth: {
			user: from,
			pass: 'AaSs12345'
		},
	});

	// 设置邮件内容
	const mailOptions = {
		from: from, // 发件地址
		to: to, // 收件列表
		subject: subject, // 标题
		html: body // html 内容
	}
	// 发送邮件
	smtpTransport.sendMail(mailOptions, function (error, response) {
		if (error) {
			console.log(error);
		} else {
			console.log("Message sent: " + response.message);
		}
		smtpTransport.close(); // 如果没用，关闭连接池
	});
}

// 格式化日期
export function formatDate(date, format) {
	let str = format;
	let o = {
		'M+': date.getMonth() + 1,
		'D+': date.getDate(),
		'h+': date.getHours(),
		'm+': date.getMinutes(),
		's+': date.getSeconds()
	};
	if (/(Y+)/.test(format)) {
		str = str.replace(RegExp.$1, date.getFullYear().toString().substr(4 - RegExp.$1.length));
	}
	for (let k in o) {
		if (new RegExp('(' + k + ')').test(format)) {
			str = str.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(o[k].toString().length));
		}
	}
	return str;
}

// 获取公众号的原始id
export function getOriginalDeviceSn(devcieSn) {
	if (devcieSn === '') {
		return '';
	}
	let arry = devcieSn.split('_');
	return arry[0].concat('_', arry[1]);
}

// 获取中项目中执行
export function getRootDir() {
	return process.cwd();
}


// 传入的参数定义
export function paramDic(host, sn) {
	return {
		host: host,
		sn: sn
	}
}

// 获取appid
export function getAppId(configList, host) {
	let appId = ''
	for (let i = 0; i < configList.length; i++) {
		if (configList[i].host === host) {
			appId = configList[i].app_id;
			break;
		}
	}
	return appId;
}

/**
 * 对sql语句进行对应的拦截操作
 */
export function sqlInterceptor(sql) {
	const white_list = ['select'];
	const black_list = ['update', 'delete', 'drop', 'alert', 'device_uuid_list'];

	for (let x in white_list) {
		if (sql.toLocaleLowerCase().indexOf(white_list[x]) == -1) {
			console.log('white_list error x=', x);
			return false;
		}
	}
	for (let x in black_list) {
		if (sql.toLocaleLowerCase().indexOf(black_list[x]) != -1) {
			console.log('black_list error x=', x);
			return false;
		}
	}
	return true;
}

// 初始化数据缓存存储
export function getCategoryList(list) {
	let categoryList = [];
	// 存储需要添加的类别标志
	let map = new Map();
	for (let index = 0; index < list.length; index++) {
		const item = list[index];
		if (map.get(item.album_group_id)) {
			let group = map.get(item.album_group_id);
			if (group.album_list.length < 6) {
				let album = {
					album_id: item.album_id,
					name: item.name,
					img_url: item.img_url,
				}
				group.album_list.push(album);
				map.set(item.album_group_id, group);
			}
		} else {
			let album = {
				album_id: item.album_id,
				name: item.name,
				img_url: item.img_url,
			}
			let group = { album_group_id: item.album_group_id, album_group_name: item.group_name, album_group_url: item.image_name, album_list: [album] };
			map.set(item.album_group_id, group);
		}
	}
	map.forEach(function (value, key) {
		categoryList.push(value);
	})
	return categoryList;
}

export function checkNumber(value) {
	const reg = /^[0-9]+.?[0-9]*$/;
	return reg.test(value);
}

